package core;

import material.Material;
import math.Euler;
import math.Matrix4;
import math.Quaternion;
import math.Vector3;

import java.util.ArrayList;

public class Mesh {
    public Geometry geometry;
    public ArrayList<Mesh> children;
    public Material material;
    public float[] position;
    public Euler rotation;
    public float[] scale;
    public Quaternion quaternion;
    public Mesh parent;

    public Matrix4 matrixWorld;
    public Matrix4 matrix;


    public Mesh(Geometry geometry, Material material){
        this.geometry = geometry;
        this.material = material;

        this.position = new float[]{0, 0, 0};
        this.scale = new float[]{1, 1, 1};
        this.rotation = new Euler();

        this.quaternion = new Quaternion().setFromEuler( this.rotation);

        this.children = new ArrayList<Mesh>();
        this.matrix = new Matrix4();
        this.matrixWorld = new Matrix4();
        this.updateMatrix();
    }

    public void updateMatrix(){
        this.matrix.compose( new Vector3().fromArray(this.position), this.quaternion, new Vector3().fromArray(this.scale) );
        this.updateMatrixWorld();
    }

    public void updateMatrixWorld () {

        // this.updateMatrix();

        if ( this.parent == null ) {

            this.matrixWorld = this.matrix.clone();

        } else {

            this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );

        }

        this.updateChildrenMatrixWorld();

    }

    public void updateChildrenMatrixWorld(){

        int size = this.children.size();
        for(int i=0; i<size; i++){
            this.children.get(i).updateMatrixWorld();
        }

    }
}
